import os
import subprocess
import json
import sys

# 获取当前脚本的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 添加 scripts 目录到 Python 路径
scripts_dir = os.path.join(current_dir, "scripts")
sys.path.insert(0, scripts_dir)

try:
    from data_processor import DataProcessor
    from kg_builder import KnowledgeGraphBuilder

    print("成功导入模块")
except ImportError as e:
    print(f"导入模块失败: {e}")
    print(f"当前 Python 路径: {sys.path}")
    print(f"scripts 目录内容: {os.listdir(scripts_dir) if os.path.exists(scripts_dir) else '目录不存在'}")
    exit(1)


def main():
    # 1. 配置路径（修改为你的实际路径）
    DATA_DIR = "data"  # 你的data文件夹路径
    PROCESSED_DIR = "processed"  # 处理后的数据目录
    NEO4J_URI = "bolt://localhost:7687"
    NEO4J_USER = "neo4j"
    NEO4J_PASSWORD = "123456"  # 替换为你的Neo4j密码

    # 2. 数据处理
    print("===== 开始数据处理 =====")
    processor = DataProcessor(data_dir=DATA_DIR)
    processor.process_spo_data()  # 解析SPO三元组
    processor.save_processed_data(output_dir=PROCESSED_DIR)

    # 3. 导入知识图谱到Neo4j
    print("\n===== 开始导入知识图谱 =====")
    # 加载处理后的数据
    entities_path = os.path.join(PROCESSED_DIR, "entities.json")
    relations_path = os.path.join(PROCESSED_DIR, "relations.json")

    if not os.path.exists(entities_path) or not os.path.exists(relations_path):
        print("错误: 处理后的数据文件不存在")
        return

    with open(entities_path, "r", encoding="utf-8") as f:
        entities = json.load(f)

    with open(relations_path, "r", encoding="utf-8") as f:
        relations = json.load(f)

    # 导入Neo4j
    try:
        kg_builder = KnowledgeGraphBuilder(uri=NEO4J_URI, user=NEO4J_USER, password=NEO4J_PASSWORD)
        kg_builder.create_constraints()  # 注意方法名已更改
        kg_builder.import_entities(entities)
        kg_builder.import_relations(relations)
        kg_builder.close()
    except Exception as e:
        print(f"导入知识图谱失败: {e}")
        return

    # 4. 启动后端服务
    print("\n===== 启动后端服务 =====")
    print("访问 http://localhost:5000 查看知识图谱")

    # 检查 app.py 是否存在
    app_path = os.path.join(current_dir, "app.py")
    if not os.path.exists(app_path):
        print(f"错误: {app_path} 不存在")
        print("请确保 app.py 文件在项目根目录中")
        return

    try:
        # 使用 subprocess.Popen 而不是 run，这样不会阻塞
        subprocess.Popen([sys.executable, app_path])
        print("后端服务已启动，按 Ctrl+C 停止服务")

        # 等待用户中断
        try:
            while True:
                pass
        except KeyboardInterrupt:
            print("\n正在停止服务...")

    except Exception as e:
        print(f"启动后端服务失败: {e}")


if __name__ == "__main__":
    main()